<template>
	<div class="log-container">
		<!-- 搜索区域 -->
		<el-card class="search-card">
			<el-form :model="queryParams" :inline="true" size="medium">
				<el-form-item label="模块">
					<el-input v-model="queryParams.module" placeholder="请输入模块名称" clearable @clear="handleSearch"
						@keyup.enter="handleSearch" />
				</el-form-item>

				<el-form-item label="操作">
					<el-input v-model="queryParams.operation" placeholder="请输入操作名称" clearable @clear="handleSearch"
						@keyup.enter="handleSearch" />
				</el-form-item>

				<el-form-item label="操作人">
					<el-input v-model="queryParams.operatorName" placeholder="请输入操作人姓名" clearable @clear="handleSearch"
						@keyup.enter="handleSearch" />
				</el-form-item>

				<el-form-item label="状态">
					<el-select v-model="queryParams.status" placeholder="请选择状态" clearable @change="handleSearch">
						<el-option label="全部" value="" />
						<el-option label="成功" value="SUCCESS" />
						<el-option label="失败" value="FAILED" />
					</el-select>
				</el-form-item>

				<el-form-item>
					<el-button type="primary" @click="handleSearch">
						<i class="el-icon-search"></i> 搜索
					</el-button>
					<el-button @click="handleReset">
						<i class="el-icon-refresh"></i> 重置
					</el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<!-- 日志表格 -->
		<el-card class="table-card">
			<div class="table-header">
				<h3>系统操作日志</h3>
				<div>
					<el-button size="small" @click="refreshData">
						<i class="el-icon-refresh"></i> 刷新
					</el-button>
				</div>
			</div>

			<el-table :data="operationList" v-loading="loading" border stripe style="width: 100%"
				@row-click="handleRowClick">
				<el-table-column type="index" width="50" label="序号" align="center" />

				<el-table-column prop="id" label="ID" width="80" align="center" />

				<el-table-column prop="module" label="模块" width="120" align="center">
					<template #default="{ row }">
						<el-tag size="small" :type="getModuleTagType(row.module)">
							{{ row.module }}
						</el-tag>
					</template>
				</el-table-column>

				<el-table-column prop="operation" label="操作" width="150" align="center" />

				<el-table-column prop="description" label="描述" width="180" show-overflow-tooltip />

				<el-table-column prop="requestMethod" label="请求方法" width="100" align="center">
					<template #default="{ row }">
						<el-tag size="small" :type="getMethodTagType(row.requestMethod)">
							{{ row.requestMethod }}
						</el-tag>
					</template>
				</el-table-column>

				<el-table-column prop="operatorName" label="操作人" width="120" align="center">
					<template #default="{ row }">
						{{ row.operatorName || '未知' }}
					</template>
				</el-table-column>

				<el-table-column prop="status" label="状态" width="80" align="center">
					<template #default="{ row }">
						<el-tag size="small" :type="row.status === 'SUCCESS' ? 'success' : 'danger'">
							{{ row.status === 'SUCCESS' ? '成功' : '失败' }}
						</el-tag>
					</template>
				</el-table-column>

				<el-table-column prop="executionTime" label="耗时(ms)" width="100" align="center">
					<template #default="{ row }">
						<span :class="getExecutionTimeClass(row.executionTime)">
							{{ row.executionTime }}
						</span>
					</template>
				</el-table-column>

				<el-table-column prop="ipAddress" label="IP地址" width="140" show-overflow-tooltip />

				<el-table-column prop="createdTime" label="操作时间" width="180" align="center">
					<template #default="{ row }">
						{{ formatDateTime(row.createdTime) }}
					</template>
				</el-table-column>

				<el-table-column label="操作" width="100" align="center" fixed="right">
					<template #default="{ row }">
						<el-button type="primary" size="mini" @click.stop="showDetail(row)">
							详情
						</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页 -->
			<div class="pagination-container">
				<el-pagination v-model:current-page="queryParams.page" v-model:page-size="queryParams.size"
					:page-sizes="[10, 20, 30, 50]" :total="total" layout="total, sizes, prev, pager, next, jumper"
					@size-change="handleSizeChange" @current-change="handleCurrentChange" />
			</div>
		</el-card>

		<!-- 详情对话框 -->
		<el-dialog v-model="detailDialogVisible" title="日志详情" width="800px" @close="handleDialogClose">
			<el-descriptions :column="2" border>
				<el-descriptions-item label="ID">{{ currentLog.id }}</el-descriptions-item>
				<el-descriptions-item label="模块">{{ currentLog.module }}</el-descriptions-item>
				<el-descriptions-item label="操作">{{ currentLog.operation }}</el-descriptions-item>
				<el-descriptions-item label="描述">{{ currentLog.description }}</el-descriptions-item>
				<el-descriptions-item label="请求URL" :span="2">
					<el-text type="primary">{{ currentLog.requestUrl }}</el-text>
				</el-descriptions-item>
				<el-descriptions-item label="请求方法">
					<el-tag :type="getMethodTagType(currentLog.requestMethod)">
						{{ currentLog.requestMethod }}
					</el-tag>
				</el-descriptions-item>
				<el-descriptions-item label="状态">
					<el-tag :type="currentLog.status === 'SUCCESS' ? 'success' : 'danger'">
						{{ currentLog.status }}
					</el-tag>
				</el-descriptions-item>
				<el-descriptions-item label="耗时">
					<span :class="getExecutionTimeClass(currentLog.executionTime)">
						{{ currentLog.executionTime }} ms
					</span>
				</el-descriptions-item>
				<el-descriptions-item label="操作人">
					{{ currentLog.operatorName || '未知' }}
				</el-descriptions-item>
				<el-descriptions-item label="操作类型">
					{{ currentLog.operatorType || '未知' }}
				</el-descriptions-item>
				<el-descriptions-item label="IP地址">
					{{ currentLog.ipAddress }}
				</el-descriptions-item>
				<el-descriptions-item label="操作时间">
					{{ formatDateTime(currentLog.createdTime) }}
				</el-descriptions-item>
				<el-descriptions-item label="请求参数" :span="2">
					<div class="log-content">
						<pre>{{ formatContent(currentLog.requestParams) }}</pre>
					</div>
				</el-descriptions-item>
				<el-descriptions-item label="返回结果" :span="2">
					<div class="log-content">
						<pre>{{ formatContent(currentLog.responseResult) }}</pre>
					</div>
				</el-descriptions-item>
				<el-descriptions-item v-if="currentLog.errorMessage" label="错误信息" :span="2">
					<div class="log-content error">
						<pre>{{ formatContent(currentLog.errorMessage) }}</pre>
					</div>
				</el-descriptions-item>
				<el-descriptions-item label="用户代理" :span="2">
					<div class="log-content">
						{{ currentLog.userAgent }}
					</div>
				</el-descriptions-item>
			</el-descriptions>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="detailDialogVisible = false">关闭</el-button>
					<el-button type="primary" @click="detailDialogVisible = false">
						确定
					</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script>
	import http  from '../../utils/request'
	import {
		ElMessage
	} from 'element-ui'
	
	export default {
		name: 'OperationLog',
		data() {
			return {
				operationList: [],
				loading: false,
				total: 0,
				queryParams: {
					page: 1,
					size: 10,
					module: '',
					operation: '',
					operatorName: '',
					status: ''
				},
				detailDialogVisible: false,
				currentLog: {}
			}
		},
		created() {
			this.getOperationList()
		},
		methods: {
			async getOperationList() {
				this.loading = true
				try {
					const params = {
						...this.queryParams
					}
					const resp = await http.get('/admin/getOperationList', {
						params
					})
					if (resp.data.code === 1) {
						this.operationList = resp.data.data.list || []
						this.total = resp.data.data.total || 0
					} else {
						ElMessage.error(resp.data.msg || '获取日志列表失败')
					}
				} catch (error) {
					console.error('获取日志列表失败:', error)
					ElMessage.error('获取日志列表失败')
				} finally {
					this.loading = false
				}
			},

			handleSearch() {
				this.queryParams.page = 1
				this.getOperationList()
			},

			handleReset() {
				this.queryParams = {
					page: 1,
					size: 10,
					module: '',
					operation: '',
					operatorName: '',
					status: ''
				}
				this.getOperationList()
			},

			handleSizeChange(size) {
				this.queryParams.size = size
				this.getOperationList()
			},

			handleCurrentChange(page) {
				this.queryParams.page = page
				this.getOperationList()
			},

			refreshData() {
				this.getOperationList()
				ElMessage.success('刷新成功')
			},

			showDetail(row) {
				this.currentLog = {
					...row
				}
				this.detailDialogVisible = true
			},

			handleRowClick(row) {
				this.showDetail(row)
			},

			handleDialogClose() {
				this.currentLog = {}
			},

			formatDateTime(dateTime) {
				if (!dateTime) return ''
				const date = new Date(dateTime)
				return date.toLocaleString('zh-CN', {
					year: 'numeric',
					month: '2-digit',
					day: '2-digit',
					hour: '2-digit',
					minute: '2-digit',
					second: '2-digit'
				}).replace(/\//g, '-')
			},

			formatContent(content) {
				if (!content) return '无'
				// 简单的格式化处理
				try {
					return content
						.replace(/=/g, ' = ')
						.replace(/\(/g, '(\n  ')
						.replace(/, /g, ',\n  ')
						.replace(/\)/g, '\n)')
				} catch (e) {
					return content
				}
			},

			getModuleTagType(module) {
				const types = {
					'Admin': 'primary',
					'Login': 'success',
					'User': 'warning',
					'System': 'info'
				}
				return types[module] || 'default'
			},

			getMethodTagType(method) {
				const types = {
					'GET': 'success',
					'POST': 'primary',
					'PUT': 'warning',
					'DELETE': 'danger'
				}
				return types[method] || 'info'
			},

			getExecutionTimeClass(time) {
				if (time > 1000) return 'execution-time-slow'
				if (time > 500) return 'execution-time-medium'
				return 'execution-time-fast'
			}
		}
	}
</script>

<style scoped>
	.log-container {
		padding: 20px;
	}

	.search-card {
		margin-bottom: 20px;
	}

	.table-card {
		margin-bottom: 20px;
	}

	.table-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
	}

	.table-header h3 {
		margin: 0;
		color: #333;
	}

	.pagination-container {
		display: flex;
		justify-content: flex-end;
		margin-top: 20px;
	}

	.log-content {
		max-height: 200px;
		overflow-y: auto;
		padding: 8px;
		background-color: #f5f5f5;
		border-radius: 4px;
		font-family: 'Consolas', 'Monaco', monospace;
		font-size: 12px;
		white-space: pre-wrap;
		word-break: break-all;
	}

	.log-content.error {
		background-color: #fff2f0;
		border: 1px solid #ffccc7;
	}

	.execution-time-fast {
		color: #67c23a;
		font-weight: bold;
	}

	.execution-time-medium {
		color: #e6a23c;
		font-weight: bold;
	}

	.execution-time-slow {
		color: #f56c6c;
		font-weight: bold;
	}

	:deep(.el-descriptions__label) {
		font-weight: bold;
		width: 100px;
	}

	:deep(.el-descriptions__content) {
		min-width: 200px;
	}
</style>